<template>
  <div class="card">
    <h2 class="text-lg font-bold">户籍人口及增速</h2>
    <div class="chart-container bg-white rounded-lg shadow p-2 pb-5">
      <LineChart :data="registeredPopulationData" :options="chartOptions" class="w-full h-48" />
    </div>
  </div>
</template>

<script setup>
import { ref } from 'vue'
// 预测函数 - 基于历史数据线性回归
const predictValue = (historicalData) => {
  const actualData = historicalData.filter((value) => value !== null)
  const n = actualData.length
  if (n < 2) return null
  let sumX = 0
  let sumY = 0
  let sumXY = 0
  let sumX2 = 0
  for (let i = 0; i < n; i++) {
    const x = i + 1 // 年份索引（2021年为1）
    const y = actualData[i]
    sumX += x
    sumY += y
    sumXY += x * y
    sumX2 += x * x
  }
  const slope = (n * sumXY - sumX * sumY) / (n * sumX2 - sumX * sumX)
  const intercept = (sumY - slope * sumX) / n
  return slope * (n + 1) + intercept // 预测下一年数据
}
// 初始化图表数据（含预测值）
const initChartData = () => {
  // 2021-2024年实际数据
  const populationData = [870, 890, 910, 930]
  const growthData = [2.3, 2.3, 2.2, 2.2]
  // 计算2025年预测值
  const populationForecast = predictValue(populationData).toFixed(0)
  const growthForecast = predictValue(growthData).toFixed(1)
  return {
    labels: ['2021年', '2022年', '2023年', '2024年', '2025年(预测)'],
    datasets: [
      {
        label: '户籍人口(万人)',
        data: [...populationData, Number(populationForecast)],
        backgroundColor: (context) =>
          context.dataIndex === 4 ? 'rgba(54, 162, 235, 0.5)' : 'rgba(54, 162, 235, 0.9)',
        borderColor: (context) =>
          context.dataIndex === 4 ? 'rgba(54, 162, 235, 0.7)' : 'rgba(54, 162, 235, 1)',
        borderWidth: 1,
        type: 'bar',
        borderRadius: 4,
        barPercentage: 0.6,
        categoryPercentage: 0.7,
        yAxisID: 'y',
      },
      {
        label: '增速(%)',
        data: [...growthData, Number(growthForecast)],
        backgroundColor: 'rgba(255, 159, 64, 0.8)',
        borderColor: (context) =>
          context.dataIndex === 4 ? 'rgba(255, 159, 64, 0.6)' : 'rgba(255, 159, 64, 1)',
        borderWidth: 2,
        borderDash: (context) => (context.dataIndex === 4 ? [5, 5] : []),
        type: 'line',
        fill: false,
        tension: 0.3,
        pointRadius: (context) => (context.dataIndex === 4 ? 6 : 4),
        pointBackgroundColor: (context) =>
          context.dataIndex === 4 ? 'rgba(255, 159, 64, 0.6)' : '#fff',
        pointBorderColor: 'rgba(255, 159, 64, 1)',
        pointBorderWidth: 2,
        yAxisID: 'y1',
      },
    ],
  }
}
// 户籍人口及增速图表数据
const registeredPopulationData = ref(initChartData())
// 通用图表配置
const chartOptions = ref({
  responsive: true,
  maintainAspectRatio: false,
  interaction: {
    mode: 'index',
    intersect: false,
  },
  scales: {
    x: {
      grid: { display: false },
      ticks: {
        color: '#666',
        maxRotation: 0, // 禁止x轴标签倾斜
        minRotation: 0,
        autoSkip: false,
        maxTicksLimit: 5,
      },
    },
    y: {
      position: 'left',
      beginAtZero: true,
      grid: { color: 'rgba(0, 0, 0, 0.05)' },
      ticks: {
        color: '#666',
        callback: (value) => value + '万人',
      },
    },
    y1: {
      position: 'right',
      beginAtZero: true,
      grid: {
        color: 'rgba(0, 0, 0, 0.05)',
        drawOnChartArea: false,
      },
      ticks: {
        color: '#666',
        callback: (value) => value + '%',
      },
    },
  },
  plugins: {
    legend: {
      labels: { color: '#333' },
    },
    tooltip: {
      mode: 'index',
      intersect: false,
      backgroundColor: 'rgba(255, 255, 255, 0.9)',
      titleColor: '#333',
      bodyColor: '#666',
      borderColor: 'rgba(200, 200, 200, 1)',
      borderWidth: 1,
      padding: 10,
      boxPadding: 5,
      usePointStyle: true,
      callbacks: {
        label: (context) => {
          let label = context.dataset.label || ''
          if (label) label += ': '
          if (context.parsed.y !== null) {
            const value = context.dataset.label.includes('增速')
              ? context.parsed.y.toFixed(1)
              : context.parsed.y.toFixed(0)
            label += value + (context.dataset.label.includes('增速') ? '%' : '万人')
            if (context.dataIndex === 4) {
              label += ' (预测)'
            }
          }
          return label
        },
      },
    },
  },
})
</script>
<style scoped>
.chart-container {
  height: 200px;
}
</style>
